#include <iostream>
#include <string>
#include <mysql/mysql.h>

const std::string host = "127.0.0.1";
const std::string user = "root";
const std::string passwd = "8199470Com";
const std::string db = "test";
const unsigned int port = 3306;

int main()
{
    //查看数据库版本
    std::cout << mysql_get_client_info() << std::endl;

    //创建管理数据库的套接字文件
    MYSQL* mfp = mysql_init(nullptr);
    if(mfp == nullptr)
        std::cout << "init fail" << std::endl;

    //连接数据库
    if(!mysql_real_connect(mfp, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0)) 
        std::cout << "connect fail" << std::endl;

    //修改编码guize
    mysql_set_character_set(mfp, "utf8");
    //使用插入指令  
    const std::string str = "insert into t1 values (1, '张三'), (2, '李四'), (3, '王五')";  
    if(mysql_query(mfp, str.c_str()))   //成功返回0
        std::cout << "insert fail: " << mysql_error(mfp) << std::endl;  
    else 
        std::cout << "insert success" << std::endl;  

    //使用查询指令
    const std::string select_str = "select * from t1";
    if(mysql_query(mfp, select_str.c_str()))
        std::cout << "insert fail: " << mysql_error(mfp) << std::endl;  
    else 
        std::cout << "insert success" << std::endl;  

    //将查询结果存入MYSQL_RES中
    MYSQL_RES* res = mysql_store_result(mfp);
    //获取列名称
    int fields = mysql_num_fields(res);
    MYSQL_FIELD* field = mysql_fetch_fields(res); //获取列数
    for(int i = 0; i < fields; i++)
    {
        std::cout << field[i].name << " ";
    }
    std::cout << std::endl;
    //获取查询内容
    MYSQL_ROW row;
    for(int i = 0; i < mysql_num_rows(res); i++) //获取行数
    {
        row = mysql_fetch_row(res);  //会自动迭代
        for(int j = 0; j < fields; j++)
        {
            std::cout << row[j] << " ";
        }
        std::cout << std::endl;
    }

    //释放res空间
    mysql_free_result(res);
    
    //关闭套接字文件
    mysql_close(mfp); std::cout << "close file" << std::endl;
    return 0;
}
